package com.qust.endecryptionmanager;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.concurrent.CountDownLatch;

public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    Thread thread = null;
    Boolean flag = false;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 处理消息

        if (msg.text().equals("你好")){
            flag = false;
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        try {
                            if (flag){
                                System.out.println("堵塞");
                                break;
                            }
                            ctx.channel().writeAndFlush(new TextWebSocketFrame("Server received: " + SystemInfoUtils.getCpuInfo()));
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
            thread.start();
        }else {
            System.out.println("Received message: " + msg.text());
            System.out.println(thread);
            flag = true;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 添加连接
        System.out.println("Client connected: " + ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 断开连接
        System.out.println("Client disconnected: " + ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 异常处理
        cause.printStackTrace();
        ctx.close();
    }
}